<template>
  <div>
    <!-- 主要表格区 -->
    <div class="main_table_area">
      <!-- 功能按钮 -->
      <div class="op_btns">
        <div class="upload_container">
          <el-upload multiple :show-file-list="false" :action="mainTable.upload.action" :name="mainTable.upload.name"
            :headers="mainTable.upload.headers" :before-upload="beforeUploadHandle" :on-success="successHandle"
            :on-error="errorHandle">
            <el-button size="mini" type="success" :icon="audioAuths.uploadAudio.iconClass"
              v-show="uploadAudioStatus">上传音频</el-button>
          </el-upload>
        </div>
        <el-button plain size="mini" type="primary" icon="el-icon-video-pause"
          @click="showAudioPlayDrawer">查看正在播放</el-button>
        <el-button size="mini" type="danger" :icon="audioAuths.deleteAudios.iconClass" @click="toDeleteBatch"
          v-show="deleteAudiosStatus">批量删除</el-button>
      </div>
      <!-- 表格 -->
      <div>
        <el-table :data="mainTable.data" border highlight-current-row size="mini"
          @selection-change="mainTableSelectChangeHandle">
          <template slot="empty">
            <el-empty description="什么音频都没有"></el-empty>
          </template>
          <!-- 操作列 -->
          <el-table-column width="100px" fixed label="操作">
            <template slot-scope="{row}">
              <el-button plain size="mini" type="primary" icon="el-icon-video-play" :title="row.originalFileName"
                @click="toPlaySelectedAudio(row)">播放</el-button>
            </template>
          </el-table-column>
          <!-- 复选列 -->
          <el-table-column type="selection"></el-table-column>
          <!-- 序号列 -->
          <el-table-column type="index" label="序号"></el-table-column>
          <!-- 展开列 -->
          <el-table-column type="expand" label="详情">
            <template slot-scope="{row}">
              <el-descriptions :title="row.originalFileName" :column="1" border size="small">
                <el-descriptions-item :label="col.label" v-for="col in mainTable.expandColumns" :key="col.id">
                  <span>{{ row[col.prop] }}</span>
                </el-descriptions-item>
              </el-descriptions>
            </template>
          </el-table-column>
          <!-- 动态列 -->
          <el-table-column show-overflow-tooltip v-for="(col, index) in mainTable.columns" :key="index" :prop="col.prop"
            :label="col.label" :sortable="col.sortable" :min-width="col.minWidth">
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div style="padding:10px; display: flex; justify-content:space-around; ">
          <el-pagination hide-on-single-page layout="total, sizes, prev, pager, next, jumper" next-text="下一页"
            prev-text="上一页" @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="mainTable.page.currentPage" :page-size="mainTable.page.pageSize" :total="mainTable.page.total">
          </el-pagination>
        </div>
      </div>
    </div>

    <!-- 播放抽屉 -->
    <div>
      <el-drawer size="20%" direction="ttb" show-close :title="audioPlayDrawer.playing.originalFileName"
        :visible="audioPlayDrawer.visible" :before-close="audioPlayDrawerClose">
        <audio controls loop :src="audioPlayDrawer.playing.visitUrl" :title="audioPlayDrawer.playing.originalFileName"
          ref="audioRef"></audio>
      </el-drawer>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
export default {
  data() {
    return {
      // 主表数据
      mainTable: {
        // 动态列
        columns: [
          {
            prop: 'originalFileName',
            label: '原名',
            sortable: true,
            minWidth: '40px',
          },
          {
            prop: 'size',
            label: '大小(Kb)',
            sortable: true,
            minWidth: '30px',
          },
          {
            prop: 'createAt',
            label: '上传时间',
            sortable: true,
            minWidth: '35px',
          },
        ],
        // 展开列
        expandColumns: [
          {
            prop: 'id',
            label: 'ID',
          },
          {
            prop: 'storeAbsolutePath',
            label: '存储位置',
          },
          {
            prop: 'visitUrl',
            label: '访问地址',
          },
          {
            prop: 'mimePrefix',
            label: '类型',
          },
          {
            prop: 'size',
            label: '大小(Kb)',
          },
          {
            prop: 'extend',
            label: '后缀',
          },
          {
            prop: 'originalFileName',
            label: '原名',
          },
          {
            prop: 'storeFileName',
            label: '存储名',
          },
          {
            prop: 'createAt',
            label: '上传时间',
          },
          {
            prop: 'creatorName',
            label: '上传者',
          },
          {
            prop: 'updateAt',
            label: '更新时间',
          },
          {
            prop: 'updaterName',
            label: '更新者',
          },
        ],
        // 表格数据
        data: [],
        // 表格选中数据
        selectedData: [],
        // 分页
        page: {
          currentPage: 1,
          pageSize: 10,
          total: 0,
        },
        // 上传音频
        upload: {
          // 上传接口
          action: `${this.$axios.defaults.baseURL}admin/file/audio`,
          // 参数名
          name: 'file',
          // 请求头
          headers: {
            token: sessionStorage.getItem('token'),
          },
        },
      },

      // 音频播放抽屉
      audioPlayDrawer: {
        // 抽屉可见性
        visible: false,
        // 播放中音频
        playing: {
          visitUrl: '',
          originalFileName: '',
        }
      },
    }
  },

  computed: {
    // 借助mapGetters生成计算属性：audioAuths、uiAuthValidateIsNotNeeded
    ...mapGetters('uiAuthModule', ['audioAuths', 'uiAuthValidateIsNotNeeded']),
    // 操作可用状态计算属性
    uploadAudioStatus() {
      const { uploadAudio: { finalStatus } } = this.audioAuths
      return this.uiAuthValidateIsNotNeeded || finalStatus
    },
    deleteAudiosStatus() {
      const { deleteAudios: { finalStatus } } = this.audioAuths
      return this.uiAuthValidateIsNotNeeded || finalStatus
    },
    getAudiosStatus() {
      const { getAudios: { finalStatus } } = this.audioAuths
      return this.uiAuthValidateIsNotNeeded || finalStatus
    }
  },

  methods: {
    // #region 主要表格方法开始
    // 批量删除
    async toDeleteBatch() {
      const fileDTOList = this.mainTable.selectedData.map(m => { return { "id": m.id, 'storeAbsolutePath': m.storeAbsolutePath } })
      if (fileDTOList === null || fileDTOList.length <= 0) {
        this.$message.info("请选择要删除的音频")
      } else {
        try {
          await this.$confirm(`确定删除 ${fileDTOList.length} 条音频吗`)
          const { data: res } = await this.$axios({
            method: 'delete',
            url: '/admin/file/audio/batch',
            data: fileDTOList,
          })
          if (res.code === 0) {
            this.$message.error(res.msg)
            return
          }
          this.$message.success(`已删除 ${res.data} 条音频`)
          this.pagingGetAudios()
        } catch (e) {
          if (e != 'cancel') {
            return
          }
        }
      }
    },
    // 表格复选
    mainTableSelectChangeHandle(selection) {
      this.mainTable.selectedData = selection
    },
    // 分页获取数据
    async pagingGetAudios() {
      try {
        const { data: res } = await this.$axios.get(`/admin/file/audio/${this.mainTable.page.currentPage}/${this.mainTable.page.pageSize}`)
        if (res.code === 0) {
          this.$message.error(res.msg)
          return
        }
        this.mainTable.data = res.data.data
        this.mainTable.page.total = res.data.total
      } catch (error) {
        this.$message.error(`获取数据失败`)
        console.dir(error)
      }
    },
    // 分页组件参数改变处理
    handleSizeChange(pageSize) {
      this.mainTable.page.pageSize = pageSize
      this.pagingGetAudios()
    },
    handleCurrentChange(currentPage) {
      this.mainTable.page.currentPage = currentPage
      this.pagingGetAudios()
    },
    // 播放选中音频
    toPlaySelectedAudio(music) {
      this.audioPlayDrawer.playing = music
      this.audioPlayDrawer.visible = true
      this.$nextTick(() => {
        this.$refs.audioRef.play()
      })
    },
    // #endregion

    //#region 音频上传方法开始
    // 文件上传成功回调
    successHandle(response, file) {
      if (response.code === 0) {
        this.$message.error(response.msg)
        return
      }
      this.$message.success(`${file.name}${response.msg}`)
      this.pagingGetAudios()
    },
    // 文件上传失败回调
    errorHandle(err, file) {
      this.$message.error(`${file.name} 上传失败,${err.msg}`)
    },
    // 文件上传前文件格式校验，返回tru代表能够上传，返回false代表不能上传
    beforeUploadHandle(file) {
      if (!/^audio/i.test(file.type)) {
        this.$message.warning(`只能上传音频,文件类型为 ${file.name.substr(file.name.lastIndexOf('.') + 1)}`)
        return false
      }
      return true
    },
    //#endregion 音频上传方法结束

    //#region 音频播放方法开始
    // 显式抽屉
    showAudioPlayDrawer() {
      this.audioPlayDrawer.visible = true
    },
    // 隐藏抽屉
    audioPlayDrawerClose(done) {
      const audio = this.$refs.audioRef
      if (!audio.paused) {
        this.$confirm("音频正在播放中,是否停止播放?").then(() => {
          audio.pause()
        }).catch(() => {
          this.$message.info(`音频正在后台播放`)
        })
      }
      this.audioPlayDrawer.visible = false
      done()
    },
    //#endregion 音频播放方法结束
  },

  mounted() {
    // 若果查询音频接口可用
    if (this.getAudiosStatus) {
      this.pagingGetAudios()
    }
  },

}
</script>

<style lang="less" scoped>
.main_table_area {
  .op_btns {
    display: flex;
    justify-content: start;
    padding: 0 0 10px 0;

    .upload_container {
      display: inline-block;
      margin-right: 10px;
    }
  }
}

audio {
  width: 100%;
  border-radius: 3px;
}

audio,
audio::-webkit-media-controls-panel {
  background-color: #f1f3f4;
}
</style>